<?php

namespace app\controller;

use Yii;
use yii\web\Controller;
use app\models\TForumTopic;
use app\models\TForum;
use app\models\TForumComment;
use app\models\TForumTopicStatus;
use yii\helpers\ArrayHelper;
use app\models\TBaseUserProfile;
use app\models\TForumUserBrowsingHistory;
use app\models\TForumTopicVote;
use app\models\TForumTopicUserVote;
use Faker\Provider\Uuid;
use yii\db\Transaction;
use yii\helpers\Html;
use app\models\TCourseInfo;
use app\models\TCourseMember;
use app\models\TCourseNotice;
use app\models\TBaseUser;
use yii\db\Exception;
use app\common\ImageHelper;

class ClassroomForumController extends Controller{
    public $enableCsrfValidation = false;
    public function init(){
        parent::init();
        header('Access-Control-Allow-Origin: *');
    }
    public function actionTopicCourseList()
    {
        $error      = [];
        $img        = [];
        $from  = isset($_REQUEST['from']) && !empty($_REQUEST['from']) ? $_REQUEST['from'] : '';
        $tcourseId  = isset($_REQUEST['tcourseId']) && !empty($_REQUEST['tcourseId']) ? $_REQUEST['tcourseId'] : $error[] = '课程id不能为空';
        $scheduleId  = isset($_REQUEST['scheduleId']) && !empty($_REQUEST['scheduleId']) ? $_REQUEST['scheduleId'] : $error[] = '课表id不能为空';
        $page = isset($_REQUEST['page']) && !empty($_REQUEST['page']) ? $_REQUEST['page'] : 1;
        $pageSize = isset($_REQUEST['pageSize']) && !empty($_REQUEST['pageSize']) ? $_REQUEST['pageSize'] : 10;
        $type_id = isset($_REQUEST['type_id']) && !empty($_REQUEST['type_id']) ? $_REQUEST['type_id'] : 0;
        $content = isset($_REQUEST['content']) && !empty($_REQUEST['content']) ? $_REQUEST['content'] : '';
        $forum_info = empty($error) ? TForum::find()->select('id')->where(['course_id'=>$tcourseId,'del_flag'=>0])->one() : FALSE;
        $search_content=!empty($_REQUEST['searchContent']) ? $_REQUEST['searchContent']:'';
        $offset = 0;
        if(!empty($error)){
            $result = array(
                "msg"   => "操作失败",
                "ver"   => "1.5.0",
                'data'  => $error,
                'code'  => '601'
            );
        }else if(empty ($forum_info)){
            $result = [
                'msg'   => '课程论坛未创建',
                'ver'   => "1.5.0",
                'data'  => ['课程论坛尚未创建'],
                'code'  => '404'
            ];
        }else{
            $forum_id = $info['forum_id'] = $forum_info->id;
            $activityType = ['not_vote'=>[],'vote'=>[]];
            foreach ($activityType AS $key => $value) {
                $andWhere = $key == 'not_vote' ? ['IN','type',['activityType.discussion','activityType.answer']] : ['type' => 'activityType.vote'];
                $topicList = TForumTopic::find()
                    ->select(['id','create_time'])
                    ->where(['forum_id'=>$forum_id,'del_flag'=>0])
                    ->andWhere($andWhere)
                    ->orderBy('create_time DESC')
                    ->asArray()
                    ->all();
                $topicIdList = empty($topicList) ? '' : ArrayHelper::getColumn($topicList, 'id');
                $comment = empty($topicIdList) ? 0 : TForumComment::find()->where(['IN','topic_id',$topicIdList])->count();
                $last_time = empty($topicIdList) ? '暂无' : $topicList[0]['create_time'];
                $activityType[$key]['topic']    = empty($topicIdList) ? 0 : count($topicIdList);
                $activityType[$key]['comment']  = empty($topicIdList) ? 0 : $comment + count($topicIdList);
                $activityType[$key]['last_time']= $last_time;
            }
            $info['activityType'] = $activityType;

            $whereInfo = ['tft.forum_id' => $forum_id,'tft.del_flag' => '0'];
            switch ($type_id){
                case 1:
                    $whereInfo = array_merge_recursive($whereInfo,['tft.type' => 'activityType.discussion']);
                    break;
                case 2:
                    $whereInfo = array_merge_recursive($whereInfo,['tft.type' => 'activityType.answer']);
                    break;
                case 3:
                    $whereInfo = array_merge_recursive($whereInfo,['tft.type' => 'activityType.vote']);
                    break;
            }
            $andWhereInfo = empty($content) ? '1=1' : ['OR',['LIKE','tft.content',$content],['LIKE','tft.title',$content],['LIKE','tft.content', Html::encode($content)]];
            $andWhereInfo2=($from=='current') ? ['type' => 'activityType.vote'] : '1=1';//来源确定展示内容
            $info['totalCount'] = TForumTopic::find()
                ->alias('tft')
                ->leftJoin(TForumTopicStatus::tableName().' AS tfts','tft.id=tfts.topic_id')
                ->where($whereInfo)
                ->andWhere($andWhereInfo)
                ->andWhere($andWhereInfo2)
                ->count();

            if(!empty($page) && !empty($pageSize)) {
                $offset  = ($page-1)*$pageSize;
            }

            $selectList = [
                'distinct( tft.id)',
                'tft.create_by',
                'tft.type',
                'tft.vote_type',
                'tft.create_time',
                'tft.title',
                'tft.content',
                'tfts.preposition_status'
            ];
            $orderBy = 'tfts.preposition_status DESC,tfts.create_time DESC,tft.create_time DESC';
            if(!empty($search_content)){
                $searchsql=" tft.title like '%".$search_content."%'";
            }else{
                $searchsql=" 1=1 ";
            }
            $info['list'] = TForumTopic::find()
                ->alias('tft')
                ->select($selectList)
                ->leftJoin(TForumTopicStatus::tableName().' AS tfts','tft.id=tfts.topic_id')
                ->leftJoin('t_course_schedule_forum AS tcsf','tcsf.topic_id=tft.id')
                ->where($whereInfo)
                ->andWhere($andWhereInfo)
                ->andWhere($andWhereInfo2)//来源确定展示内容
                ->andWhere("tcsf.t_course_schedule_id='".$scheduleId."'")
                ->andWhere($searchsql)
                ->orderBy($orderBy)
                ->limit($pageSize)
                ->offset($offset)
                ->asArray()
                ->all();
            foreach ($info['list'] AS $key => $value) {
                $word_reg = '/<\/?.*?>/si';
                $word_temp = preg_replace($word_reg, '', $value['content']);
                $img_reg = '/<img((?!src).)*src[\s]*=[\s]*[\'"](?<src>[^\'"]*)[\'"]/i';
                preg_match_all($img_reg, $value['content'],$img);
                $user_info = TBaseUserProfile::findOne(['user_id'=>$value['create_by']]);
                $info['list'][$key]['count_num'] = TForumComment::find()->where(['del_flag'=>0,'topic_id'=>$value['id']])->count();
                $info['list'][$key]['hits'] = TForumUserBrowsingHistory::findOne(['topic_id'=>$value['id']])['hits'] ?? 0;
                $info['list'][$key]['photo'] = empty($user_info) || empty($user_info->url_image) ? '' : (substr($user_info->url_image, 0,5) == 'files' ? Yii::$app->params['fileUrl'].$user_info->url_image : $user_info->url_image);
                $info['list'][$key]['pet_name'] = empty($user_info) ? '匿名用户' : $user_info->pet_name;
                $info['list'][$key]['content'] = ['word'=>$word_temp,'img'=>$img['src']];

                if($value['type'] == 'activityType.vote'){
                    $info['list'][$key]['type'] = 3;
                    $info['list'][$key]['vote_list'] =  TForumTopicVote::find()->select('id,sort,content,count,percentage')->where(['topic_id'=>$value['id'],'del_flag'=>0])->orderBy('sort ASC')->asArray()->all();
                    $info['list'][$key]['voted_id'] = TForumTopicUserVote::find()->select('vote_id')->where(['topic_id'=>$value['id'],'create_by'=>$value['create_by']])->column();
                }else{
                    $info['list'][$key]['type'] = $value['type'] == 'activityType.discussion' ? 1 : 2;
                    $info['list'][$key]['vote_list'] = [];
                    $info['list'][$key]['voted_id'] = [];
                }
                $last_reply_tip_sql="SELECT create_by,create_time from t_forum_comment where topic_id=:tip ORDER BY create_time DESC LIMIT 1";
                $last_reply_topic = Yii::$app->db->createCommand($last_reply_tip_sql)->bindValue(':tip', $value['id'])->queryOne();
                $last_reply_user_sql="select pet_name from t_base_user_profile where user_id=:uid";
                $last_reply_user = Yii::$app->db->createCommand($last_reply_user_sql)->bindValue(':uid', $last_reply_topic['create_by'])->queryScalar();
                $info['list'][$key]['last_reply_user']  = $last_reply_user;
                $info['list'][$key]['last_reply_time']  = $last_reply_topic['create_time'];
            }
            $result     = array(
                "msg"   => "查找成功",
                "ver"   => "1.5.0",
                'data'  => $info,
                'code'  => '200'
            );
        }
        Yii::$app->end(json_encode($result));
    }
    public function actionForumCommentList()
    {
        $error      = [];
        $topic_id   = isset($_REQUEST['topic_id']) && !empty($_REQUEST['topic_id']) ? $_REQUEST['topic_id'] : $error[] = '回复主题id不能为空';
        $user_id    = isset($_REQUEST['user_id']) && !empty($_REQUEST['user_id']) ? $_REQUEST['user_id'] : $error[] = '用户id不能为空';
        $page       = isset($_REQUEST['page']) && !empty($_REQUEST['page']) ? $_REQUEST['page'] : '';
        $pageSize   = isset($_REQUEST['pageSize']) && !empty($_REQUEST['pageSize']) ? $_REQUEST['pageSize'] : '';
        $source     = isset($_REQUEST['source']) && !empty($_REQUEST['source']) ? $_REQUEST['source'] : 'Mobile';
        $topic_info = empty($error) ? TForumTopic::findOne(['id'=>$topic_id,'del_flag'=>0]) : FALSE;
        $tcourseId = isset($_REQUEST['tcourseId']) && !empty($_REQUEST['tcourseId']) ? $_REQUEST['tcourseId'] : $error[] = '课程id不能为空';
        if(!empty($error)){
            $result = array(
                "msg"   => "操作失败",
                "ver"   => "1.5.0",
                'data'  => $error,
                'code'  => '601'
            );
        }else if(empty ($topic_info)){
            $result = [
                'msg'   => "主题id错误",
                'ver'   => '1.5.0',
                'data'  => ['回复主题id不存在'],
                'code'  => '404'
            ];
        }else{
            $history = TForumUserBrowsingHistory::find()->where(['topic_id' => $topic_id])->one();
            if(empty($history)){
                $history = new TForumUserBrowsingHistory();
                $history->id = Uuid::uuid();
                $history->topic_id = $topic_id;
                $history->hits = 0;
                $history->create_time = date('Y-m-d H:i:s');
                $history->del_flag = 0;
            }
            $history->hits = $history->hits + 1;
            $history->save();
            $topic = $topic_info->toArray();
            $user_info = TBaseUserProfile::findOne(['user_id'=>$topic['create_by']]);
            $topic['pet_name'] = empty($user_info) ? '匿名用户' : $user_info->pet_name;
            $topic['photo'] = empty($user_info) || empty($user_info->url_image) ? '' : Yii::$app->params['fileUrl'].$user_info->url_image;
            if($topic['type'] == 'activityType.vote') {
                $vote = TForumTopicVote::find()->select('id,topic_id,sort,content,count,percentage')->where(['topic_id'=>$topic_id,'del_flag'=>0])->orderBy('sort ASC')->asArray()->all();
                //查询投票者相关信息
                foreach ($vote as $k=>&$v){
                    $sql="SELECT
	u.username,p.pet_name,p.student_no,c.class_name
FROM
	t_base_user_profile p
LEFT JOIN t_forum_topic_user_vote v ON p.user_id = v.create_by
LEFT JOIN t_base_user u ON p.user_id = u.id
LEFT JOIN t_course_member m ON m.user_id=u.id
LEFT JOIN t_base_class c ON m.class_id=c.id
WHERE
	v.del_flag = 0
AND c.del_flag=0
AND p.del_flag=0
AND u.del_flag=0
AND m.del_flag=0
AND c.del_flag=0
AND v.vote_id =:vote_id
AND v.topic_id =:topic_id
AND m.course_id=:courseId
GROUP BY u.id 
union all 
SELECT
	u.username,p.pet_name,'--' as student_no,'--' as class_name 
FROM
	t_base_user_profile p
LEFT JOIN t_forum_topic_user_vote v ON p.user_id = v.create_by
LEFT JOIN t_base_user u ON p.user_id = u.id
WHERE
	v.del_flag = 0
AND p.del_flag=0
and p.type='userType.teacher' 
AND u.del_flag=0
AND v.vote_id =:vote_id
AND v.topic_id =:topic_id
GROUP BY u.id
";
                    $userInfo=\yii::$app->db->createCommand($sql)->bindValues([':vote_id'=>$v['id'],':topic_id'=>$topic_id,'courseId'=>$tcourseId])->queryAll();
                    $v['voteUserInfo']=$userInfo;
                }
                $voted_id = TForumTopicUserVote::find()->select('vote_id')->where(['topic_id'=>$topic_id,'create_by'=>$user_id])->column();
            }
            $topic['preposition_status'] = TForumTopicStatus::find()->where(['topic_id'=>$topic['id'],'preposition_status'=>'yesOrNo.yes','del_flag'=>0])->exists();
            $sql    = "SELECT %s FROM t_forum_comment WHERE topic_id='".$topic_id."' AND pid IS NULL AND del_flag=0 ORDER BY create_time DESC ";
            $count  = Yii::$app->db->createCommand(sprintf($sql,'COUNT(*)'))->queryScalar();
            if(!empty($page) && !empty($pageSize)) {
                $offset = ($page-1)*$pageSize;
                $sql   .= " LIMIT {$offset},{$pageSize}";
            }
            $list1  = Yii::$app->db->createCommand(sprintf($sql,'*'))->queryAll();
            $sql2   = "SELECT id,pid,content,create_by,create_time FROM t_forum_comment WHERE topic_id='".$topic_id."' AND pid != '' AND del_flag=0 ORDER BY create_time DESC ";
            $list2  = Yii::$app->db->createCommand($sql2)->queryAll();
            $list   = array_merge($list1,$list2);
            foreach ($list AS $key => $value) {
                $list[$key]['current_pet_name'] = static::getRealNameByUserId($value['create_by']);
                $list[$key]['current_url_img']  = static::getPhotoByUserId($value['create_by']);
                $list[$key]['parent_pet_name']  = static::getRealNameByCommentId($value['pid']);
            }
            $active_user = TBaseUserProfile::find()->select(['user_id','pet_name','school_id','url_image'])->where(['user_id'=>$user_id,'del_flag'=>0])->asArray()->one();
            if(!empty($active_user['url_image'])){
                $active_user['url_image']= \Yii::$app->params['fileUrl'].$active_user['url_image'];
            }
            $treeData = static::valueForTree($list);
            $treeData = ArrayHelper::getColumn($treeData, function($element){
                if(!isset($element['list']) || empty($element['list'])){
                    $element['list'] = 0;
                }
                return $element;
            });
            $info   = [
                'topic' => $topic,
                'count' => $count,
                'list' => $treeData,
                'vote' => isset($vote) ? $vote : '',
                'voted_id' => isset($voted_id) ? $voted_id : '',
                'active_user' => $active_user,

            ];
            $result = [
                "msg"   => "查找成功",
                "ver"   => "1.5.0",
                'data'  => $info,
                'code'  => '200'
            ];
        }
        Yii::$app->end(json_encode($result));
    }
    public function actionForumCommentAdd()
    {
        $error          = [];
        $topic_id       = isset($_REQUEST['topic_id']) && !empty($_REQUEST['topic_id']) ? $_REQUEST['topic_id'] : $error[] = '回复主题不能为空';
        $content        = isset($_REQUEST['content']) && !empty($_REQUEST['content']) ? $_REQUEST['content'] : $error[] = '内容不能为空';
        $create_by      = isset($_REQUEST['create_by']) && !empty($_REQUEST['create_by']) ? $_REQUEST['create_by'] : $error[] = '创建者id不能为空';
        $pid            = isset($_REQUEST['pid']) && !empty($_REQUEST['pid']) ? $_REQUEST['pid'] : NULL;
        $create_time    = date('Y-m-d H:i:s');

        $user_info      = empty($error) ? TBaseUser::findOne(['id'=>$create_by,'del_flag'=>0]) : FALSE;
        $topic_info     = empty($error) ? TForumTopic::find()->select('title,forum_id,old_id')->where(['id'=>$topic_id,'del_flag'=>0])->one() : FALSE;
        $forum_info     = empty($topic_info) ? FALSE : TForum::find()->select('course_id')->where(['id'=>$topic_info->forum_id,'del_flag'=>0])->one();
        if(!empty($error)){
            $result = array(
                "msg"   => "操作失败",
                "ver"   => "1.5.0",
                'data'  => $error,
                'code'  => '601'
            );
        }else if(empty ($user_info)){
            $result = [
                'msg'   => '用户不存在',
                'ver'   => '1.5.0',
                'data'  => ['用户信息不存在'],
                'code'  => '404'
            ];
        }else if(empty ($topic_info)){
            $result = [
                'msg'   => '回复主题id错误',
                'ver'   => '1.5.0',
                'data'  => ['回复主题id不存在'],
                'code'  => '404'
            ];
        }else if(empty ($forum_info)){
            $result = [
                'msg'   => '所属论坛不存在',
                'ver'   => '1.5.0',
                'data'  => ['所属论坛信息不存在'],
                'code'  => '404'
            ];
        }else{
            $sql="select type from t_forum_topic where id=:id";
            $type=\yii::$app->db->createCommand($sql)->bindValues([':id'=>$topic_id])->queryScalar();
            if($type=='activityType.discussion'){
                $topic_type=1;
            }elseif($type=='activityType.answer'){
                $topic_type=2;
            }else if($type=='activityType.vote'){
                $topic_type=3;
            }
            $model = new TForumComment();
            $model->id          = Uuid::uuid();
            $model->topic_id    = $topic_id;
            $model->pid         = $pid;
            $model->type        = $type;
            $model->user_name   = $user_info->username;
            $model->content     = $content;
            $model->status      = "";
            $model->create_by   = $create_by;
            $model->create_time = $create_time;
            $model->del_flag    = 0;
            $model->old_id  = $model->id;
            $topicInfo = [
                'course_id' => $forum_info->course_id,
                'forum_id' => $topic_info->forum_id,
                'topic_title' => $topic_info->title,
                'topic_old_id' => $topic_info->old_id
            ];
            if($model->validate() && $model->save()){
                $model->type=$topic_type;
                $result = [
                    "msg"=> "操作成功",
                    "ver"=> "1.5.0",
                    'data'=> array_merge($model->attributes,$topicInfo),
                    'code'=>'200'
                ];
            }else {
                $result = [
                    'msg'   => '操作失败',
                    'ver'   => '1.5.0',
                    'data'  => $model->getErrors(),
                    'code'  => '400'
                ];
            }
        }
        Yii::$app->end(json_encode($result));
    }
    /*
     * 课堂教学新建帖子
     * */
    public function actionForumTopicAdd()
    {
        $error          = [];
        $tcourseId      = isset($_REQUEST['tcourseId']) && !empty($_REQUEST['tcourseId']) ? $_REQUEST['tcourseId'] : $error[] = '课程id不能为空';
        $type           = isset($_REQUEST['type']) && !empty($_REQUEST['type']) ? $_REQUEST['type'] : $error[] = '发帖类型不能为空';
        $title          = isset($_REQUEST['title']) && !empty($_REQUEST['title']) ? $_REQUEST['title'] : $error[] = '标题不能为空';
        $content        = isset($_REQUEST['content']) && !empty($_REQUEST['content']) ? $_REQUEST['content'] : $error[] = '内容不能为空';
        $create_by      = isset($_REQUEST['create_by']) && !empty($_REQUEST['create_by']) ? $_REQUEST['create_by'] : $error[] = '创建者id不能为空';
        $schedule_id    = isset($_REQUEST['scheduleId']) && !empty($_REQUEST['scheduleId']) ? $_REQUEST['scheduleId'] : $error[] = '课表id不能为空';
        $item_id        = isset($_REQUEST['item_id']) && !empty($_REQUEST['item_id']) ? $_REQUEST['item_id'] : "";
        $item_top_id    = isset($_REQUEST['item_top_id']) && !empty($_REQUEST['item_top_id']) ? $_REQUEST['item_top_id'] : "";
        if($type == 3) {
            $begin_time = isset($_REQUEST['begin_time']) && !empty($_REQUEST['begin_time']) ? date('Y-m-d H:i:s', strtotime($_REQUEST['begin_time'])) : $error[] = '开始时间不能为空';
            $end_time   = isset($_REQUEST['end_time']) && !empty($_REQUEST['end_time']) ? date('Y-m-d H:i:s', strtotime($_REQUEST['end_time'])) : $error[] = '结束时间不能为空';
            $vote_type  = isset($_REQUEST['vote_type']) && !empty($_REQUEST['vote_type']) ? $_REQUEST['vote_type'] : $error[] = '投票类型不能为空';
            $vote_list  = isset($_REQUEST['vote_list'])  && !empty($_REQUEST['vote_list']) ? json_decode($_REQUEST['vote_list'],JSON_FORCE_OBJECT) : $error[] = '投票选项列表不能为空';
            //校验开始时间与结束时间
            if($begin_time==$end_time){
                $result = [
                    "msg"   => "操作失败",
                    "ver"   => "1.5.0",
                    'data'  => ['开始时间不能等于结束时间'],
                    'code'  => '601'
                ];
                \yii::$app->end(json_encode($result));
            }elseif($begin_time>$end_time){
                $result = [
                    "msg"   => "操作失败",
                    "ver"   => "1.5.0",
                    'data'  => ['开始时间不能大于结束时间'],
                    'code'  => '601'
                ];
                \yii::$app->end(json_encode($result));
            }
        }
        $status         = 'activityStatus.ongoing';
        $create_time    = date('Y-m-d H:i:s', time());

        $user_info      = empty($error) ? TBaseUser::findOne(['id'=>$create_by]) : FALSE;
        $tcourse_info   = empty($error) ? TCourseInfo::find()->select('id')->where(['id'=>$tcourseId,'del_flag'=>0])->one() : FALSE;
        $forum_info     = empty($tcourse_info) ? FALSE : TForum::find()->select('id')->where(['course_id'=>$tcourseId,'del_flag'=>0])->one();
        if(!empty($error)){
            $result = [
                "msg"   => "操作失败",
                "ver"   => "1.5.0",
                'data'  => $error,
                'code'  => '601'
            ];
        }else if(empty ($tcourse_info)){
            $result = [
                'msg'   => '课程信息获取错误',
                'ver'   => '1.5.0',
                'data'  => ['课程id不存在'],
                'code'  => '404'
            ];
        }else if(empty ($forum_info)){
            $result = [
                "msg"   => "课程论坛信息获取错误",
                "ver"   => "1.5.0",
                'data'  => ['课程论坛id获取错误'],
                'code'  => '404'
            ];
        }else if(empty ($user_info)){
            $result = [
                'msg'   => '用户信息错误',
                'ver'   => '1.5.0',
                'data'  => ['用户信息不存在'],
                'code'  => '404'
            ];
        }else{
            if($type==3){
                $vote_flag=true;
                foreach ($vote_list AS $key1 => $val1){
                    //校验内容不能为空
                    if(empty($val1['content'])){
                        $vote_flag=false;
                    }
                }
                if(!$vote_flag){
                    $result = [
                        "msg"   => "操作失败",
                        "ver"   => "1.5.0",
                        'data'  => ['投票选项内容不能为空'],
                        'code'  => '404'
                    ];
                    Yii::$app->end(json_encode($result));
                }
                $num=0;
                foreach($vote_list as $k1=>$v1){
                    $content_box[]=$v1['content'];
                    $num++;
                }
                $content_box=array_unique($content_box);
                $content_num=count($content_box);
                if($content_num!=$num){
                    $result = [
                        "msg"   => "操作失败",
                        "ver"   => "1.5.0",
                        'data'  => ['投票选项内容不能相同'],
                        'code'  => '404'
                    ];
                    Yii::$app->end(json_encode($result));
                }
            }
            $forum_id       = $forum_info->id;
            $success        = [];
            $transaction = Yii::$app->db->beginTransaction();
            try{
                $model = new TForumTopic();
                $model->id          = Uuid::uuid();
                $model->forum_id    = $forum_id;
                $model->item_id     = $item_id;
                $model->item_top_id = $item_top_id;
                $model->type        = $type == 3 ? "activityType.vote" : ($type == 2 ? "activityType.answer" : "activityType.discussion");
                $model->title       = Html::encode($title);
                $model->content     = $content;
                $model->status      = $status;
                $model->user_name   = $user_info->username;
                $model->token       = "";
                $model->create_by   = $create_by;
                $model->create_time = $create_time;
                $model->del_flag    = 0;
                $model->old_id  = $model->id;
                if($type == 3) {
                    $model->begin_time  = $begin_time;
                    $model->end_time    = $end_time;
                    $model->vote_type   = $vote_type;
                }
                if($model->validate() && $model->save()){
                    $history = new TForumUserBrowsingHistory();
                    $history->id            = Uuid::uuid();
                    $history->topic_id      = $model->id;
                    $history->hits          = 0;
                    $history->create_time   = $model->create_time;
                    $history->del_flag      = 0;
                    $success[] = $history->save(false);

                    if($type == 3) {
                        foreach ($vote_list AS $key => $val) {
                            $voteModel = new TForumTopicVote();
                            $voteModel->id          = Uuid::uuid();
                            $voteModel->topic_id    = $model->id;
                            $voteModel->sort        = $val['sort'];
                            $voteModel->content     = $val['content'];
                            $voteModel->create_by   = $create_by;
                            $voteModel->create_time = $create_time;
                            $voteModel->del_flag    = 0;
                            $success[]  = $voteModel->save();
                        }
                    }
                    //关联帖子与课堂教学数据表
                    $sql="insert into t_course_schedule_forum (
id,
t_course_id,
t_course_schedule_id,
forum_id,
topic_id,
create_by,
create_time,
del_flag
) values(
:id,
:t_course_id,
:schedule_id,
:forum_id,
:topic_id,
:create_by,
:create_time,
0
)";
                    $res=\yii::$app->db->createCommand($sql)->bindValues([
                        ':id'=>Uuid::uuid(),
                        ':t_course_id'=>$tcourseId,
                        ':schedule_id'=>$schedule_id,
                        ':forum_id'=>$forum_id,
                        ':topic_id'=>$model->id,
                        ':create_by'=>$create_by,
                        ':create_time'=>date('Y-m-d H:i:s',time()),
                    ])->execute();
                    if(in_array(FALSE, $success)){
                        throw new Exception('error2');
                    }
                    if(!$res){
                        throw new Exception('error3');
                    }
                    $result = array(
                        "msg"   => "添加成功",
                        "ver"   => "1.5.0",
                        'data'  => $model->attributes,
                        'code'  => '200'
                    );
                    $transaction->commit();
                } else {
                    throw new Exception('error1');
                }

            }catch (Exception $e) {
                $message = $e->getMessage();
                $error[] = $model->getErrors();
                if($message == 'error1'){
                    $result = array(
                        "msg"   => "操作失败",
                        "ver"   => "1.5.0",
                        'data'  => $error,
                        'code'  =>'400'
                    );
                }else{
                    $result = array(
                        "msg"   => "添加失败",
                        "ver"   => "1.5.0",
                        'data'  => array('添加失败'),
                        'code'  => '400'
                    );
                }
                $transaction->rollBack();
            }
        }
        Yii::$app->end(json_encode($result));
    }
    static private function getRealNameByCommentId($pid) {
        $sql    = "SELECT u.pet_name FROM t_base_user_profile AS u INNER JOIN t_forum_comment AS c ON u.user_id=c.create_by WHERE c.id='".$pid."'";
        $result = Yii::$app->db->createCommand($sql)->queryOne();
        return empty($result) ? '匿名用户' : $result['pet_name'];
    }

    static private function getPhotoByUserId($user_id) {
        $result = '';
        $result = TBaseUserProfile::findOne(['user_id'=>$user_id]);
        $result = empty($result) || empty($result->url_image) ? '' : Yii::$app->params['fileUrl'].$result->url_image;
        return $result;
    }
    static public function getRealNameByUserId($user_id) {
        $result = '';
        $result = TBaseUserProfile::findOne(['user_id'=>$user_id]);
        $result = empty($result) ? '匿名用户' : $result->pet_name;
        return $result;
    }
    static private function valueForTree(array $data,$pid = NULL,$level = 1)
    {
        static $tmp = [];
        foreach ($data AS $key => $value) {
            if($pid == NULL && $level == 1 && $value['pid'] == NULL) {
                $k = count($tmp);
                $tmp[$k] = array_merge_recursive($value,['defaultInfo' => ['num' => 2, 'title' => '显示剩余']]);
                unset($data[$key]);
                self::valueForTree($data,$value['id'],2);
            }else if ($pid !== NULL && $level == 2 && $value['pid'] == $pid ){
                $k = count($tmp);
                $tmp[$k-1]['list'][] = $value;
                unset($data[$key]);
                self::valueForTree($data,$value['id'],2);
            }else{
                continue;
            }
        }
        return $tmp;
    }
}